<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/22
 * Time: 13:25
 */

namespace common\business\excel;
use common\business\CommonHelper;
use PHPExcel_IOFactory;
use PHPExcel;
use PHPExcel_Worksheet;

use common\business\file\FileHandler;

abstract class ExcelFileHandler extends FileHandler
{
    /**
     * 处理文件
     * @param callback|null $writeBackHandler
     * @return boolean
     */
    protected  function process($writeBackHandler = null)
    {

        try {
            $reader = null;
            if (strtolower($this->file->file_extension) == 'csv') {
                $reader = PHPExcel_IOFactory::createReader('csv');
            } else if (strtolower($this->file->file_extension) == 'xls' || strtolower($this->file->file_extension) == 'xlsx') {
                //            $this->filename = $this->file->file_fullname;
                $readerType = PHPExcel_IOFactory::identify($this->filename);
                $reader = PHPExcel_IOFactory::createReader($readerType);
                //            $reader  = PHPExcel_IOFactory::createReader('Excel2007');
                //            $reader  = PHPExcel_IOFactory::createReader('Excel5');
            } else {
                $this->addError('process', 'File extension not matched.');
                return false;
            }
            $excelFile = $reader->load($this->filename);
            $currentSheet = $excelFile->getActiveSheet();
            $startRow = $this->start_row;
            $highestRows = $currentSheet->getHighestRow();//取得最大的行号
            $this->rows_total = $highestRows - $startRow + 1;

            //        if ($writeBackHandler){
//            $paramArr = [
//                'totalCount' => $this->rows_total,
//                'finishCount' => 0,
//            ];
//            call_user_func_array($writeBackHandler, $paramArr);
//        }
        } catch (\Exception $e) {
            $errMsg = CommonHelper::getExceptionMsg($e);
            if ($writeBackHandler) {
                $paramArr = [
                    'totalCount' => $this->rows_total,
                    'finishCount' => $this->rows_insert + $this->rows_cover + $this->rows_skip + $this->rows_error,
                    'message' => $errMsg,
                ];
                call_user_func_array($writeBackHandler, $paramArr);
            }
        }

        return $this->processExcel($objExcel, $currentSheet, $startRow, $highestRows, $writeBackHandler);
    }

    /**
     * excel导入处理
     *
     * @param PHPExcel           $objExcel
     * @param PHPExcel_Worksheet $currentSheet
     * @param int                $startRow
     * @param int                $highestRows
     * @param callback|null      $writeBackHandler
     * @return boolean
     */
    abstract protected function processExcel(&$objExcel, &$currentSheet, $startRow, $highestRows, $writeBackHandler = null);
}